package com.ljy.day1;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class Crawler3_post_2 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
        // 声明List集合,封装表单中的参数
        ArrayList<NameValuePair> params = new ArrayList<>();
        // 设置请求地址:http://yun.itheima.com/search?keys=Java
        params.add(new BasicNameValuePair("keys","Java"));
        // 创建表单的Entity对象,第一个参数就是封装好的表单数据,第二个参数就是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf8");
        // 设置表单的Entity对象到Post请求中
        httpPost.setEntity(formEntity);
        System.out.println(httpPost);//POST http://yun.itheima.com/search HTTP/1.1
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpPost);
            // 解析响应
            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
